package com.example.customizedgroupmessage;

import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class SMSTemplateCall extends Activity{
	ArrayList<Template> arrTemplate;
	DBHelper mHelper;
	SQLiteDatabase db;
	
	// inner class (adapter)
	public class TemplateCallAdapter extends BaseAdapter{	
		LayoutInflater mInflater;
		ArrayList<Template> items;
		Context _context;
		
		public TemplateCallAdapter(Context context, ArrayList<Template> contentListItem){
			mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			items = contentListItem;
			_context = context;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return items.size();
		}
		
		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return items.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			final int pos = position;
			int res =R.layout.sms_template_item;
			convertView =mInflater.inflate(res, parent, false);
			
			TextView date =(TextView)convertView.findViewById(R.id.textDate);
			date.setText(items.get(position).getId());
			
			TextView content =(TextView)convertView.findViewById(R.id.textContent);
			//content.setText(items.get(position).getOriginalMsg());
			content.setText("");
			items.get(position).analyzeMsg();

			for(int i =0; i < items.get(position).analyzedMsg.length ; i++){
				if(items.get(position).analyzedMsg[i].equals("#name")){
					Drawable d = getResources().getDrawable(R.drawable.name);
					d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
					ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
					SpannableString sText = new SpannableString(items.get(position).analyzedMsg[i]);
					sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					content.append(sText);
				}
				else if(items.get(position).analyzedMsg[i].equals("#status")){
					Drawable d = getResources().getDrawable(R.drawable.status);
					d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
					ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
					SpannableString sText = new SpannableString(items.get(position).analyzedMsg[i]);
					sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					content.append(sText);
				}
				else if(items.get(position).analyzedMsg[i].equals("#org")){
					Drawable d = getResources().getDrawable(R.drawable.org);
					d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
					ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
					SpannableString sText = new SpannableString(items.get(position).analyzedMsg[i]);
					sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					content.append(sText);
				}
				else if(items.get(position).analyzedMsg[i].equals("#custom")){
					Drawable d = getResources().getDrawable(R.drawable.custom);
					d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
					ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
					SpannableString sText = new SpannableString(items.get(position).analyzedMsg[i]);
					sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
					content.append(sText);
				}
				else{
					content.append(items.get(position).analyzedMsg[i]);
				}
			}
			
			Button btnSel = (Button)convertView.findViewById(R.id.btnDel);
			btnSel.setFocusable(false);
			Drawable dr = getResources().getDrawable(R.drawable.btn_call);
			//btnSel.setBackground(dr);
			btnSel.setBackgroundDrawable(dr);
			
			// 선택 버튼 클릭 이벤트
			btnSel.setOnClickListener(new Button.OnClickListener() {
				public void onClick(View v){
					// 이 액티비티를 시작하게 한 인텐트를 호출한다.
					Intent intent = getIntent();
					// 인텐트에 문자메시지 내용을 넣은 후, 다시 인텐트를 반환한다.
					intent.putExtra("originalMsg", items.get(pos).getOriginalMsg());
					setResult(RESULT_OK, intent);
	                finish(); // 액티비티 종료
				}
			});
			return convertView;
		}	
	} // inner class
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.sms_template_box);
		
		TextView textSel = (TextView)findViewById(R.id.tmplSelect);
		textSel.setText("불러오기");
		
		//템플릿 배열 생성
		arrTemplate = new ArrayList<Template>();
		arrTemplate.clear();
		
		Template temp;
		String _id = null;
		String msg = null;
		
		mHelper = new DBHelper(this);
		db = mHelper.getReadableDatabase();
		Cursor cursor;
		cursor = db.rawQuery("SELECT * FROM smstemplate ORDER BY _id DESC", null);
		while (cursor.moveToNext()) {
			_id = cursor.getString(0);
			msg = cursor.getString(1);
			
			temp =  new Template();
			temp.setId(_id);
			temp.setOriginalMsg(msg);
			arrTemplate.add(temp);
		}
		cursor.close();
		mHelper.close();
		
		
		
		//어댑터 준비
		TemplateCallAdapter myTemplateAdapter= new TemplateCallAdapter(this, arrTemplate);
		ListView myTemplateList;
		
		//어댑터연결
		myTemplateList = (ListView)findViewById(R.id.listSMSTemplate);
		myTemplateList.setAdapter(myTemplateAdapter);
		myTemplateList.setOnItemClickListener(mItemClickListener);
	}
	AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			AlertDialog dialog = createDialogBox(position, id);
		    dialog.show();
			
		}
	};

	
AlertDialog createDialogBox(int position, long id){
		LayoutInflater li = LayoutInflater.from(this);
		View smsTemplateDetail = li.inflate(R.layout.detail, null);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(this);	
	
		builder.setTitle(arrTemplate.get(position).getId());
		builder.setView(smsTemplateDetail);
		
		TextView txtMsg = (TextView)smsTemplateDetail.findViewById(R.id.txtMsg);
		//txtMsg.setText(arrTemplate.get(position).getOriginalMsg());
		txtMsg.setText("");
		arrTemplate.get(position).analyzeMsg();

		for(int i =0; i < arrTemplate.get(position).analyzedMsg.length ; i++){
			if(arrTemplate.get(position).analyzedMsg[i].equals("#name")){
				Drawable d = getResources().getDrawable(R.drawable.name);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(arrTemplate.get(position).analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				txtMsg.append(sText);
			}
			else if(arrTemplate.get(position).analyzedMsg[i].equals("#status")){
				Drawable d = getResources().getDrawable(R.drawable.status);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(arrTemplate.get(position).analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				txtMsg.append(sText);
			}
			else if(arrTemplate.get(position).analyzedMsg[i].equals("#org")){
				Drawable d = getResources().getDrawable(R.drawable.org);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(arrTemplate.get(position).analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				txtMsg.append(sText);
			}
			else if(arrTemplate.get(position).analyzedMsg[i].equals("#custom")){
				Drawable d = getResources().getDrawable(R.drawable.custom);
				d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
				ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
				SpannableString sText = new SpannableString(arrTemplate.get(position).analyzedMsg[i]);
				sText.setSpan(span, 0, sText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
				txtMsg.append(sText);
			}
			else{
				txtMsg.append(arrTemplate.get(position).analyzedMsg[i]);
			}
		}
	    
		builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
			}
		});

		AlertDialog dialog = builder.create();

		return dialog;
	}	
}